package com.kl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kl.em.ConstantEnum;
import com.kl.em.Result;
import com.kl.entity.Role;
import com.kl.entity.Staff;
import com.kl.mapper.MenuRoleMapper;
import com.kl.mapper.RoleMapper;
import com.kl.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2021-10-29
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private MenuRoleMapper menuRoleMapper;

    @Override
    @Transactional
    public Result addRole(Role role, Integer[] mids) {

        // 增加角色表
        int i = roleMapper.insert(role);
        if(i <= 0){
            return Result.build(ConstantEnum.ERROR);
        }
        // 角色的主键id
        Integer rid = role.getRid();
        // 增加中间表
        int i2 = menuRoleMapper.insertBatch(rid, mids);

        if(i2 <= 0){
            return Result.build(ConstantEnum.ERROR);
        }
        return Result.build(ConstantEnum.SUCCESS);
    }

    @Override
    @Transactional
    public Role toUpdate(Integer rid) {

        Role role = roleMapper.selectById(rid);
        return role;
    }

    @Override
    @Transactional
    public Result updateRole(Role role, Integer[] mids) {
        // 修改角色信息
        int i = roleMapper.updateById(role);
        if(i <= 0){
            return Result.build(ConstantEnum.ERROR);
        }
        // 删除
        QueryWrapper wrapper = new QueryWrapper<Staff>();
        wrapper.eq("rid",role.getRid());
        menuRoleMapper.delete(wrapper);
        // 增加
        int i2 = menuRoleMapper.insertBatch(role.getRid(), mids);
        if(i2 <= 0){
            return Result.build(ConstantEnum.ERROR);
        }
        return Result.build(ConstantEnum.SUCCESS);
    }

    @Override
    @Transactional
    public Result deleteByRid(Integer rid) {
        int i = roleMapper.deleteById(rid);
        if(i <= 0){
            return Result.build(ConstantEnum.ERROR);
        }
        // 删除
        QueryWrapper wrapper = new QueryWrapper<Staff>();
        wrapper.eq("rid",rid);
        menuRoleMapper.delete(wrapper);
        return Result.build(ConstantEnum.SUCCESS);
    }
}
